package com.zhiqian.community.service;

import com.zhiqian.community.entity.Comment;
import com.zhiqian.community.entity.Event;
import com.zhiqian.community.event.EventProducer;
import com.zhiqian.community.util.CommunityConstant;
import com.zhiqian.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

@Service
public class LikeService implements CommunityConstant {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private CommentService commentService;

    /**
     * 点赞
     *
     * @param userId
     * @param entityType
     * @param entityId
     */
    public void like(Integer userId, int entityType, Integer entityId, Integer targetId) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        String countKey = RedisKeyUtil.getUserHaveLikeCountKey(targetId);
        Boolean member = redisTemplate.opsForSet().isMember(entityLikeKey, userId);
        //开启redis事务
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                redisOperations.multi();
                if (member) {
                    redisOperations.opsForSet().remove(entityLikeKey, userId);
                    redisOperations.opsForValue().decrement(countKey);
                } else {
                    redisOperations.opsForSet().add(entityLikeKey, userId);
                    redisOperations.opsForValue().increment(countKey);
                }
                return redisOperations.exec();
            }
        });
        if (!member){
            Event likeEvent = createLikeEvent(userId, entityType, entityId, targetId);
            eventProducer.fireEvent(likeEvent);
        }
        if (entityType==ENTITY_TYPE_POST){
            redisTemplate.opsForSet().add(RedisKeyUtil.getVariationPostKey(),entityId);
        }
    }

    /**
     * 查询某实体被赞的数量
     *
     * @param entityType
     * @param entityId
     * @return
     */
    public Long queryEntityLikeCount(int entityType, Integer entityId) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().size(entityLikeKey);
    }

    /**
     * 查询用户对某实体的点赞状态
     *
     * @param userId
     * @param entityType
     * @param entityId
     * @return
     */
    public int queryEntityLikeStatus(Integer userId, int entityType, Integer entityId) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().isMember(entityLikeKey, userId) ? 1 : 0;
    }

    /**
     * 查询用户获赞数量
     *
     * @param userId
     * @return
     */
    public int selectUserHaveLikeCount(Integer userId) {
        Integer count = (Integer) redisTemplate.opsForValue().get(RedisKeyUtil.getUserHaveLikeCountKey(userId));
        return count == null ? 0 : count;
    }

    private Event createLikeEvent(Integer sourceId, int entityType, Integer entityId, Integer targetId){
        Event event = new Event();
        event.setTopic(TOPIC_LIKE);
        event.setTargetId(targetId);
        event.setSourceId(sourceId);
        event.setEntityType(entityType);
        event.setEntityId(entityId);
        if (entityType==ENTITY_TYPE_COMMENT){
            Comment comment = commentService.selectCommentById(entityId);
            if (comment.getEntityType()==ENTITY_TYPE_POST) {
                event.setData("postId", comment.getEntityId());
            }else {
                Comment parentComment = commentService.selectCommentById(comment.getEntityId());
                event.setData("postId",parentComment.getEntityId());
            }
        }else {
            event.setData("postId",entityId);
        }
        return event;
    }
}
